package com.github.live.component;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.github.live.R;
import com.github.live.adapter.LiveChannelGroupAdapter;
import com.github.live.adapter.LiveChannelItemAdapter;
import com.github.live.manager.ChannelsManager;
import com.github.live.manager.LiveConfig;
import com.github.live.base.VisibleComponent;
import com.github.live.manager.LiveInitializer;
import com.owen.tvrecyclerview.widget.TvRecyclerView;
import com.owen.tvrecyclerview.widget.V7LinearLayoutManager;

import java.lang.ref.WeakReference;

/**
 * @ClassName LiveMenuView
 * @description:
 * @author: biao532
 * @create: 2023-12-08 15:00
 * @Version 1.0
 **/
public class LiveMenuView extends LinearLayout implements VisibleComponent {
    private TvRecyclerView mGroupGridView;
    private TvRecyclerView mChannelGridView;
    private LiveChannelGroupAdapter liveChannelGroupAdapter;
    private LiveChannelItemAdapter liveChannelItemAdapter;
    private Handler mHandler;
    private LiveInitializer initializer;
    private WeakReference<LiveMenuView> _this = new WeakReference<>(this);
    private Runnable mHideChannelListRun = new Runnable() {
        @Override
        public void run() {
            LiveMenuView __this = _this.get();
            if (__this == null) {
                return;
            }
            if (__this.getVisibility() != View.VISIBLE) {
                return;
            }
            __this.setVisibility(View.GONE);
        }
    };

    public LiveMenuView(Context context) {
        super(context);
        init(context);
    }

    public LiveMenuView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    @Override
    public void show() {
        mGroupGridView.scrollToPosition(initializer.getChannelsManager().getCurrentGroupIndex());
        mGroupGridView.setSelection(initializer.getChannelsManager().getCurrentGroupIndex());
        mChannelGridView.scrollToPosition(initializer.getChannelsManager().getCurrentChannelIndex());
        mHandler.removeCallbacks(mHideChannelListRun);
        setVisibility(VISIBLE);
    }

    @Override
    public void hide(long delayed) {
        mHandler.removeCallbacks(mHideChannelListRun);
        mHandler.postDelayed(mHideChannelListRun, delayed);
    }

    public void setHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.component_live_menu, this);
        mGroupGridView = findViewById(R.id.mGroupGridView);
        mChannelGridView = findViewById(R.id.mChannelGridView);

        initializer = LiveInitializer.getInitializer();
        initChannelGroupView();
        initLiveChannelView();
        initChannels();
    }

    private void initChannels() {
        liveChannelGroupAdapter.setData(initializer.getChannelsManager().getLiveChannelGroups());
        int groupIndex = initializer.getChannelsManager().getCurrentGroupIndex();
        renderChannels(groupIndex);

    }
    private void initChannelGroupView() {
        mGroupGridView.setHasFixedSize(true);
        mGroupGridView.setLayoutManager(new V7LinearLayoutManager(getContext(), 1, false));

        liveChannelGroupAdapter = new LiveChannelGroupAdapter();
        mGroupGridView.setAdapter(liveChannelGroupAdapter);
        mGroupGridView.setOnFocusChangeListener((v,b)->{
            if (!b) {
                liveChannelGroupAdapter.setFocusedGroupIndex(-1);
            }
        });
        mGroupGridView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                mHandler.removeCallbacks(mHideChannelListRun);
                mHandler.postDelayed(mHideChannelListRun, LiveInitializer.getInitializer()
                        .getConfig()
                        .getMenuWaitfor());
            }
        });

        //电视
        mGroupGridView.setOnItemListener(new TvRecyclerView.OnItemListener() {
            @Override
            public void onItemPreSelected(TvRecyclerView parent, View itemView, int position) {
                //renderChannels(position);
            }

            @Override
            public void onItemSelected(TvRecyclerView parent, View itemView, int position) {
                renderChannels(position);
            }

            @Override
            public void onItemClick(TvRecyclerView parent, View itemView, int position) {
                renderChannels(position);
            }
        });
    }
    private void renderChannels(int groupIndex) {
        ChannelsManager cm = initializer.getChannelsManager();
        liveChannelGroupAdapter.setSelectedGroupIndex(groupIndex);
        liveChannelGroupAdapter.setFocusedGroupIndex(groupIndex);

        liveChannelItemAdapter.setData(cm.getChannelsByGroupIndex(groupIndex));
        mGroupGridView.scrollToPosition(groupIndex);
        if (groupIndex == cm.getCurrentGroupIndex()) {
            liveChannelItemAdapter.setActiveChannelIndex(cm.getCurrentChannelIndex());
            mChannelGridView.scrollToPosition(cm.getCurrentChannelIndex());
        }
        else {
            mChannelGridView.setSelectedPosition(0);
            mChannelGridView.scrollToPosition(0);
            liveChannelItemAdapter.setActiveChannelIndex(-1);
        }
    }

    private void initLiveChannelView() {
        LiveConfig config = LiveInitializer.getInitializer().getConfig();
        mChannelGridView.setHasFixedSize(true);
        mChannelGridView.setLayoutManager(new V7LinearLayoutManager(getContext(), 1, false));
        liveChannelItemAdapter = new LiveChannelItemAdapter(config.getNumberFormat());
        mChannelGridView.setAdapter(liveChannelItemAdapter);
        mChannelGridView.setOnFocusChangeListener( (v, b) -> {
            if (!b){
                liveChannelItemAdapter.setSelectedChannelIndex(-1);
            }
            else {
                mChannelGridView.setSelection(liveChannelItemAdapter.getActiveChannelIndex());
            }
        });
        mChannelGridView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                mHandler.removeCallbacks(mHideChannelListRun);
                mHandler.postDelayed(mHideChannelListRun, config.getMenuWaitfor());
            }
        });

        //电视
        mChannelGridView.setOnItemListener(new TvRecyclerView.OnItemListener() {
            @Override
            public void onItemPreSelected(TvRecyclerView parent, View itemView, int position) {
            }

            @Override
            public void onItemSelected(TvRecyclerView parent, View itemView, int position) {
                if (position < 0) return;
               channelSelect(position);
            }

            @Override
            public void onItemClick(TvRecyclerView parent, View itemView, int position) {
                if (LiveMenuView.this.getVisibility() != VISIBLE) {
                    return;
                }
                channelClick(position);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
            return false;
        }
        if (getVisibility() == View.VISIBLE) {
            mHandler.removeCallbacks(mHideChannelListRun);
            mHandler.postDelayed(mHideChannelListRun, LiveInitializer.getInitializer()
                    .getConfig()
                    .getMenuWaitfor());
        }
        return super.onKeyDown(keyCode, event);
    }

    private void channelClick(int position) {
        liveChannelItemAdapter.setActiveChannelIndex(position);
        initializer.getChannelsManager()
                .setActiveByGroupIndexAndChannelIndex(liveChannelGroupAdapter.getSelectedGroupIndex(),
                    liveChannelItemAdapter.getSelectedChannelIndex());
        this.setVisibility(GONE);
    }
    private void channelSelect(int position) {
        liveChannelItemAdapter.setSelectedChannelIndex(position);
        mChannelGridView.scrollToPosition(position);
    }
}
